package model;

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

/**
 * 
 * @author Yang Wang <yang@digitalmenubox.com>
 */
public class InventoryItem {

	// use a JSONObject as internal structure for storing data.
	private JSONObject data;

	// default constructor that contains no field mapping
	public InventoryItem() {
		data = new JSONObject();
	}

	// designated constructor that will take a json string
	// precondition: jsonString is a valid JSON string
	// postcondition: the fields of this inventory item will be set
	public InventoryItem(String jsonString) {
		data = (JSONObject) JSONValue.parse(jsonString);
	}

	public void setFieldData(Object field, Object data) {
		this.data.put(field, data);
	}

	public Object getFieldData(String field) {
		return data.get(field);
	}

	@Override
	public String toString() {
		return data.toString();
	}

	public int getNumberOfFields() {
		return data.size();
	}

	@Override
	public boolean equals(Object o) {
		if (o instanceof InventoryItem) {
			InventoryItem ii = (InventoryItem) o;
			Object myId = this.getFieldData("id");
			Object oId = ii.getFieldData("id");
			// if either of the ID field for the two inventory items are not
			// set, then they are not equal
			if (myId == null || oId != null) {
				return false;
			} else {
				// compare the two IDs
				if (myId.equals(oId)) {
					return true;
				} else {
					return false;
				}
			}
		}

		// assertion: o is not an instnace of InventoryItem
		return false;
	}

	@Override
	public int hashCode() {
		return 0;
	}

	// precondition: this.data is not null
	// postcondition: returns the "pictureN" from data
	public Object getPicture(int number) {
		return data.get("picture" + number);
	}

	public static void main(String[] args) {
		JSONObject parsed = (JSONObject) JSONValue.parse("{\"id\":\"1000\",\"year\":2010,\"make\":\"BMW\"}");
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("id", "1000");
		jsonObject.put("make", "BMW");
		jsonObject.put("year", new Integer(2010));
		// System.out.println(jsonObject);
		// System.out.println(parsed);

		InventoryItem item = new InventoryItem();
		item.setFieldData("picture1", 10000);
		System.out.println(item.getPicture(1));
	}
}
